const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken'); // 需要安装: npm install jsonwebtoken

const app = express();
const PORT = 3001;
const SECRET_KEY = 'your_secret_key_for_jwt'; // JWT密钥，实际应用中应该存储在环境变量中

// 中间件
app.use(cors());
app.use(bodyParser.json());

// 模拟用户数据
const users = [
  {
    id: 1,
    username: 'admin',
    password: '123456',
    nickname: '管理员',
    avatar: 'https://miaobi-lite.bj.bcebos.com/miaobi/5mao/b%276Jyh56yU5bCP5paw5oOF5L6j5aS05YOPXzE3Mjg5NDgyODguMjQ1MjcyMg%3D%3D%27/0.png',
    role: 'admin'
  },
  {
    id: 2,
    username: 'user',
    password: '123456',
    nickname: '普通用户',
    avatar: 'https://img1.baidu.com/it/u=3173154792,324394384&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=501',
    role: 'user'
  }
];

// 登录接口
app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  
  // 查找用户
  const user = users.find(u => u.username === username);
  
  // 验证用户名和密码
  if (!user || user.password !== password) {
    return res.status(401).json({
      code: 401,
      message: '用户名或密码错误',
      data: null
    });
  }
  
  // 生成token
  const token = jwt.sign(
    { 
      id: user.id, 
      username: user.username,
      role: user.role 
    }, 
    SECRET_KEY, 
    { expiresIn: '24h' }
  );
  
  // 返回用户信息和token
  res.json({
    code: 200,
    message: '登录成功',
    data: {
      token,
      user: {
        id: user.id,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar,
        role: user.role
      }
    }
  });
});

// 验证token的中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
  
  if (!token) {
    return res.status(401).json({
      code: 401,
      message: '未提供认证令牌',
      data: null
    });
  }
  
  jwt.verify(token, SECRET_KEY, (err, user) => {
    if (err) {
      return res.status(403).json({
        code: 403,
        message: '令牌无效或已过期',
        data: null
      });
    }
    
    req.user = user;
    next();
  });
};

// 获取当前用户信息
app.get('/api/user/info', authenticateToken, (req, res) => {
  const user = users.find(u => u.id === req.user.id);
  
  if (!user) {
    return res.status(404).json({
      code: 404,
      message: '用户不存在',
      data: null
    });
  }
  
  res.json({
    code: 200,
    message: '获取成功',
    data: {
      id: user.id,
      username: user.username,
      nickname: user.nickname,
      avatar: user.avatar,
      role: user.role
    }
  });
});

// 菜单数据
let menuList = [
  {
    id: 1,
    name: '仪表盘',
    path: '/dashboard',
    icon: 'dashboard',
    parentId: 0,
    order: 1,
    status: 1
  },
  {
    id: 2,
    name: '系统管理',
    path: '/system',
    icon: 'setting',
    parentId: 0,
    order: 2,
    status: 1
  },
  {
    id: 3,
    name: '菜单管理',
    path: '/system/menu',
    icon: 'menu',
    parentId: 2,
    order: 1,
    status: 1
  },
  {
    id: 4,
    name: '用户管理',
    path: '/system/user',
    icon: 'user',
    parentId: 2,
    order: 2,
    status: 1
  },
  {
    id: 5,
    name: '角色管理',
    path: '/system/role',
    icon: 'team',
    parentId: 2,
    order: 3,
    status: 1
  },
  {
    id: 6,
    name: '个人中心',
    path: '/profile',
    icon: 'user',
    parentId: 0,
    order: 3,
    status: 1
  }
];

// 获取菜单列表
app.get('/api/menus', (req, res) => {
  res.json({
    code: 200,
    message: '获取成功',
    data: menuList
  });
});

// 添加菜单
app.post('/api/menus', (req, res) => {
  const newMenu = {
    id: Date.now(), // 使用时间戳作为ID
    ...req.body,
    status: req.body.status || 1
  };
  menuList.push(newMenu);
  res.json({
    code: 200,
    message: '添加成功',
    data: newMenu
  });
});

// 更新菜单
app.put('/api/menus/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const index = menuList.findIndex(item => item.id === id);
  
  if (index !== -1) {
    menuList[index] = { ...menuList[index], ...req.body };
    res.json({
      code: 200,
      message: '更新成功',
      data: menuList[index]
    });
  } else {
    res.status(404).json({
      code: 404,
      message: '菜单不存在',
      data: null
    });
  }
});

// 删除菜单
app.delete('/api/menus/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const index = menuList.findIndex(item => item.id === id);
  
  if (index !== -1) {
    const deletedMenu = menuList.splice(index, 1)[0];
    res.json({
      code: 200,
      message: '删除成功',
      data: deletedMenu
    });
  } else {
    res.status(404).json({
      code: 404,
      message: '菜单不存在',
      data: null
    });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});